<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>边播边录</title>
</head>

<body>
  <div class="app">
    <button class="record-btn">record</button>
    <audio controls class="audio-player"></audio>
  </div>

  <script>
    if (navigator.mediaDevices.getUserMedia) {
      const constraints = { audio: {
        noiseSuppression: true,
        echoCancellation: true,
        autoGainControl: true,
      } };
      navigator.mediaDevices.getUserMedia(constraints).then(stream => {
        console.log("授权成功！");

        const recordBtn = document.querySelector(".record-btn");
        const audioSrc = document.querySelector(".audio-player");
        const mediaRecorder = new MediaRecorder(stream);

        let chunks = [];
        let context;
        recordBtn.onclick = () => {
          if (mediaRecorder.state === "recording") {
            if(context) context.close();
            mediaRecorder.stop();

            console.log(chunks)

            mediaRecorder.onstop = e => {
              const blob = new Blob(chunks, { type: "audio/mpeg" });
              const audioURL = window.URL.createObjectURL(blob);
              audioSrc.src = audioURL;
              audioSrc.play();
            };
            recordBtn.textContent = "record";
            console.log("录音结束");
          } else {
            audioSrc.pause();
            
            // 播放500Hz的方波
            context = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = context.createOscillator();
            oscillator.type = 'square';
            oscillator.frequency.value = 500;
            oscillator.connect(context.destination);
            oscillator.start();
            
            // 开始录音
            chunks = [];
            mediaRecorder.start();
            mediaRecorder.ondataavailable = e => chunks.push(e.data);
            console.log("录音中...");
            recordBtn.textContent = "stop";
          }
          console.log("录音器状态：", mediaRecorder.state);
        };
      }).catch(e => console.error("授权失败！", e));
    } else {
      console.error("浏览器不支持 getUserMedia");
    }
  </script>
</body>

</html>